package com.sxf.rental.controller;

import com.sxf.rental.entity.Permission;
import com.sxf.rental.service.IPermissionService;
import com.sxf.rental.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sxf
 * @since 2025-03-08
 */
@RestController
@RequestMapping("/rental/permission")
public class PermissionController {
    @Resource
    private IPermissionService permissionService;

    @GetMapping
    public Result list() {
        return Result.success().setData(permissionService.selectList());
    }

    @GetMapping("/tree")
    public Result tree() {
        List<Permission> tree = permissionService.tree();
        return Result.success().setData(tree);
    }

    @PostMapping
    public Result save(@RequestBody Permission permission){
        Integer type = permission.getPermissionType();
        if (type!=2){
            String routeUrl = permission.getRouteUrl();
            if (routeUrl.contains("/")) {
                int i = routeUrl.lastIndexOf("/");
                permission.setRouteName(routeUrl.substring(i+1));
                permission.setRoutePath(routeUrl.substring(i));
            }
        }
        return permissionService.save(permission)?Result.success():Result.fail();
    }

    @PutMapping
    public Result update(@RequestBody Permission permission){
        Integer type = permission.getPermissionType();
        if (type!=2){
            String routeUrl = permission.getRouteUrl();
            if (routeUrl.contains("/")) {
                int i = routeUrl.lastIndexOf("/");
                permission.setRouteName(routeUrl.substring(i+1));
                permission.setRoutePath(routeUrl.substring(i));
            }
        }else {
            //todo 自己加的ELSE
            permission.setRouteName("");
            permission.setRoutePath("");
        }
        return permissionService.updateById(permission)?Result.success():Result.fail();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        return permissionService.removeById(id)?Result.success():Result.fail();
    }

    @GetMapping("hasChildren/{id}")
    public Result hasChildren(@PathVariable Integer id){
        return permissionService.hasChildren(id)?Result.success().setMessage("有"):Result.success().setMessage("无");
    }
}
